<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class News extends MX_Controller
{

    private $module = 'news';
    private $table = 'news';

    function __construct()
    {
        parent::__construct();
        $this->load->model($this->module . '_model', 'model');
        $this->load->model('admincp_modules/admincp_modules_model');
        if ($this->uri->segment(1) == 'admincp') {
            if ($this->uri->segment(2) != 'login') {
                if (!$this->session->userdata('userInfo')) {
                    header('Location: ' . PATH_URL . 'admincp/login');
                    return false;
                }
                $get_module = $this->admincp_modules_model->check_modules($this->uri->segment(2));
                $this->session->set_userdata('ID_Module', $get_module[0]->id);
                $this->session->set_userdata('Name_Module', $get_module[0]->name);
            }
            $this->template->set_template('admin');
            $this->template->write('title', 'Admin Control Panel');
        }
    }

    /*------------------------------------ Admin Control Panel ------------------------------------*/
    public function admincp_index()
    {
        modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'r', 0);
        $default_func = 'created';
        $default_sort = 'DESC';
        $data = array(
            'module' => $this->module,
            'module_name' => $this->session->userdata('Name_Module'),
            'default_func' => $default_func,
            'default_sort' => $default_sort
        );
        $this->template->write_view('content', 'BACKEND/index', $data);
        $this->template->render();
    }


    public function admincp_update($id = 0)
    {
        if ($id == 0) {
            modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 0);
        } else {
            modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'r', 0);
        }
        $result[0] = array();
        if ($id != 0) {
            $result = $this->model->getDetailManagement($id);
        }
        $data = array(
            'result' => $result[0],
            'module' => $this->module,
            'id' => $id
        );
        $this->template->write_view('content', 'BACKEND/ajax_editContent', $data);
        $this->template->render();
    }

    public function admincp_save()
    {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        if ($_POST) {
            //Upload Image
            $fileName = array('image' => '');
            if ($_FILES) {
                foreach ($fileName as $k => $v) {
                    if (isset($_FILES['fileAdmincp']['error'][$k])) {
                        $typeFileImage = strtolower(substr($_FILES['fileAdmincp']['type'][$k], 0, 5));
                        if ($typeFileImage == 'image') {
                            $tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
                            $file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
                            $ext = strtolower(substr($file_name[$k], -4, 4));
                            if ($ext == 'jpeg') {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -5)) . '.jpg';
                            } else {
                                $fileName[$k] = time() . '_' . SEO(substr($file_name[$k], 0, -4)) . $ext;
                            }
                        } else {
                            print 'Only upload Image.';
                            exit;
                        }
                    }
                }
            }
            //End Upload Image

            if ($this->model->saveManagement($fileName)) {
                //Upload Image
                if ($_FILES) {
                    foreach ($fileName as $k => $v) {
                        if (isset($_FILES['fileAdmincp']['error'][$k])) {
                            $upload_path = BASEFOLDER . DIR_UPLOAD_NEWS;
                            move_uploaded_file($tmp_name[$k], $upload_path . $fileName[$k]);
                        }
                    }
                }
                //End Upload Image
                print 'success';
                exit;
            }
        }
    }

    public function admincp_delete()
    {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'd', 1);
        if ($perm == 'permission-denied') {
            print $perm;
            exit;
        }
        if ($this->input->post('id')) {
            $id = $this->input->post('id');
            $result = $this->model->getDetailManagement($id);
            modules::run('admincp/saveLog', $this->module, $id, 'Delete', 'Delete');
            $this->db->where('id', $id);
            if ($this->db->delete(PREFIX . $this->table)) {
                //Xóa hình khi Delete
                @unlink(BASEFOLDER . DIR_UPLOAD_NEWS . $result[0]->image);
                return true;
            }
        }
    }

    public function admincp_ajaxLoadContent()
    {
        $this->load->library('AdminPagination');
        $config['total_rows'] = $this->model->getTotalsearchContent();
        $config['per_page'] = $this->input->post('per_page');
        $config['num_links'] = 3;
        $config['func_ajax'] = 'searchContent';
        $config['start'] = $this->input->post('start');
        $this->adminpagination->initialize($config);

        $result = $this->model->getsearchContent($config['per_page'], $this->input->post('start'));
        $data = array(
            'result' => $result,
            'per_page' => $this->input->post('per_page'),
            'start' => $this->input->post('start'),
            'module' => $this->module
        );
        $this->session->set_userdata('start', $this->input->post('start'));
        $this->load->view('BACKEND/ajax_loadContent', $data);
    }

    public function admincp_ajaxUpdateStatus()
    {
        $perm = modules::run('admincp/chk_perm', $this->session->userdata('ID_Module'), 'w', 1);
        if ($perm == 'permission-denied') {
            print '<script type="text/javascript">show_perm_denied()</script>';
            $status = $this->input->post('status');
            $data = array(
                'status' => $status
            );
        } else {
            if ($this->input->post('status') == 0) {
                $status = 1;
            } else {
                $status = 0;
            }
            $data = array(
                'status' => $status
            );
            modules::run('admincp/saveLog', $this->module, $this->input->post('id'), 'status', 'update', $this->input->post('status'), $status);
            $this->db->where('id', $this->input->post('id'));
            $this->db->update(PREFIX . $this->table, $data);
        }

        $update = array(
            'status' => $status,
            'id' => $this->input->post('id'),
            'module' => $this->module
        );
        $this->load->view('BACKEND/ajax_updateStatus', $update);
    }

    /*------------------------------------ End Admin Control Panel --------------------------------*/


    /*------------------------------------ FRONTEND ------------------------------------*/
    public function index()
    {
        //	$data['result'] = $this->model->getNews('');
// 0: tin tuc, 1: su kien, 2: cong dong, 3: kinh nghiem
        $view_tab_1 = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 0", 'created', 'desc', 0, 10);
        $view_tab_2 = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 1", 'created', 'desc', 0, 5);
        $view_tab_3 = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 2", 'created', 'desc', 0, 5);
        $view_tab_4 = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 3", 'created', 'desc', 0, 5);

        $gallery_event = $this->model->fetch('*', "cli_gallery_category", "status = 1 AND type = 1");

        $pageSize = 10;
        $page = 1;
        $pagination = $this->pagingnews($page, $pageSize);

        $data = array(
            'items_4' => $view_tab_4,
            'items_3' => $view_tab_3,
            'items_2' => $view_tab_2,
            'items_1' => $view_tab_1,
            'gallery_event' => $gallery_event,
            'total_request' => $pagination->totalRows,
            'paging' => $pagination->paging
        );

        $this->template->write_view('content', 'FRONTEND/index', $data);
        $this->template->write('meta_keywords', META_KEY);
        $this->template->write('meta_description', META_DESC);
        $this->template->write('title', 'Tin tức | ' . getSiteName());
        $this->template->render();
    }

    public function detail($slug_detail)
    {
        $data['result'] = $this->model->getNewsDetail($slug_detail);
        if (!$data['result']) {
            header('Location: ' . PATH_URL . $this->uri->segment(1));
            exit;
        }
        $this->template->write_view('content', 'FRONTEND/detail', $data);
        $this->template->render();
    }

    function pagingnews($page, $pageSize)
    {
        $retval = new StdClass();
        $startRow = ($page - 1) * $pageSize;
        $retval->totalRows = $this->model->getTotalRecordNews();
        $retval->paging = pagination_ajax($retval->totalRows, $page, $pageSize);
        $retval->tableData = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 0", 'created', 'desc', $startRow, $pageSize);

        if ($this->input->is_ajax_request()) {
            $html = '';
            $items_2 = $retval->tableData;
            if (!empty($items_2)) {
                $count = count($items_2);
                $count2 = $count - 1;
                for ($i = 0; $i <= $count2; $i++) {
                    $imga = "";
                    if ($items_2[$i]->image != '') {
                        if ($items_2[$i]->link_img == 1) {
                            $imga = $items_2[$i]->image;
                        } else {
                            $imga = resizeImage(PATH_URL . DIR_UPLOAD_NEWS . $items_2[$i]->image, 135);
                        }
                    } else {
                        $imga = img(PATH_URL . "access/images/img/no-image.jpg", 135, 79);
                    }
                    $bien1 = $items_2[$i]->slug;
                    $ngay = date("d/m/y", strtotime($items_2[$i]->created));
                    $title = CutText($items_2[$i]->title, 50);
                    $des = CutText($items_2[$i]->description, 100);
                    $html .= '<div class="hot">
				                <div class="img left">
				                    <a href="' . $bien1 . '" target="_blank"><img src="' . $imga . '" alt="" width="135" height="79" class="dblock" /></a>
						                </div>
						                <div class="detail left">
						                    <a href="' . $bien1 . '" target="_blank"><h1>' . $title . '</h1></a>
						                    <span>Được đăng ngày ' . $ngay . '</span>
						                    <div class="clearAll"></div>
						                    <div class="des">' . $des . '
							                    </div>
							
							                </div>
					         		   </div>
		         		   <div class="clearAll"></div>
		         		   <div style="height: 10px;"></div>
		         		   <div style=" border-bottom: 1px dotted #3e3832;"></div>';
                }

            }

            $retval->html = $html;
            echo json_encode($retval);
        } else {
            return $retval;
        }
    }

    // cong dong
    function forums()
    {
        $view_tab_3 = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 2", 'created', 'desc', 0, 10);

        $gallery_event = $this->model->fetch('*', "cli_gallery_category", "status = 1 AND type = 1");

        $pageSize = 10;
        $page = 1;
        $pagination = $this->pagingforums($page, $pageSize);

        $data = array(
            'items_3' => $view_tab_3,
            'gallery_event' => $gallery_event,
            'total_request' => $pagination->totalRows,
            'paging' => $pagination->paging
        );

        $this->template->write_view('content', 'FRONTEND/forum', $data);
        $this->template->write('meta_keywords', META_KEY);
        $this->template->write('meta_description', META_DESC);
        $this->template->write('title', 'Tin tức | ' . getSiteName());
        $this->template->render();
    }

    function pagingforums($page, $pageSize)
    {
        $retval = new StdClass();

        $startRow = ($page - 1) * $pageSize;
        $retval->totalRows = $this->model->getTotalRecordForum();
        $retval->paging = pagination_ajax($retval->totalRows, $page, $pageSize);
        $retval->tableData = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 2", 'created', 'desc', $startRow, $pageSize);
        if ($this->input->is_ajax_request()) {
            $html = '';
            $items_2 = $retval->tableData;
            if (!empty($items_2)) {
                $count = count($items_2);
                $count2 = $count - 1;
                for ($i = 0; $i <= $count2; $i++) {
                    $imga = "";
                    if ($items_2[$i]->image != '') {
                        if ($items_2[$i]->link_img == 1) {
                            $imga = $items_2[$i]->image;
                        } else {
                            $imga = resizeImage(PATH_URL . DIR_UPLOAD_NEWS . $items_2[$i]->image, 135);
                        }
                    } else {
                        $imga = img(PATH_URL . "assets/images/img/no-image.jpg", 135, 79);
                    }
                    $bien1 = $items_2[$i]->slug;
                    $ngay = date("d/m/y", strtotime($items_2[$i]->created));
                    $title = CutText($items_2[$i]->title, 50);
                    $des = CutText($items_2[$i]->description, 100);
                    $html .= '<div class="hot">
				                <div class="img left">
				                    <a href="' . $bien1 . '" target="_blank"><img src="' . $imga . '" alt="" width="135" height="79" class="dblock" /></a>
						                </div>
						                <div class="detail left">
						                    <a href="' . $bien1 . '" target="_blank"><h1>' . $title . '</h1></a>
						                    <span>Được đăng ngày ' . $ngay . '</span>
						                    <div class="clearAll"></div>
						                    <div class="des">' . $des . '
							                    </div>
							
							                </div>
					         		   </div>
		         		   <div class="clearAll"></div>
		         		   <div style="height: 10px;"></div>
		         		   <div style=" border-bottom: 1px dotted #3e3832;"></div>';
                }

            }

            $retval->html = $html;
            echo json_encode($retval);
        } else {
            return $retval;
        }
    }

// su kien
    function events()
    {
        $view_tab_2 = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 1", 'created', 'desc', 0, 10);

        $gallery_event = $this->model->fetch('*', "cli_gallery_category", "status = 1 AND type = 1");

        $pageSize = 10;
        $page = 1;
        $pagination = $this->pagingevents($page, $pageSize);

        $data = array(
            'items_2' => $view_tab_2,
            'gallery_event' => $gallery_event,
            'total_request' => $pagination->totalRows,
            'paging' => $pagination->paging
        );

        $this->template->write_view('content', 'FRONTEND/event', $data);
        $this->template->write('meta_keywords', META_KEY);
        $this->template->write('meta_description', META_DESC);
        $this->template->write('title', 'Tin tức | ' . getSiteName());
        $this->template->render();
    }

    function pagingevents($page, $pageSize)
    {
        $retval = new StdClass();
        $startRow = ($page - 1) * $pageSize;
        $retval->totalRows = $this->model->getTotalRecordEvents();
        $retval->paging = pagination_ajax($retval->totalRows, $page, $pageSize);
        $retval->tableData = $this->model->fetch('*', PREFIX . $this->table, "status = 1 AND type = 1", 'created', 'desc', $startRow, $pageSize);
        if ($this->input->is_ajax_request()) {
            $html = '';
            $items_2 = $retval->tableData;
            if (!empty($items_2)) {
                $count = count($items_2);
                $count2 = $count - 1;
                for ($i = 0; $i <= $count2; $i++) {
                    $imga = "";
                    if ($items_2[$i]->image != '') {
                        if ($items_2[$i]->link_img == 1) {
                            $imga = $items_2[$i]->image;
                        } else {
                            $imga = resizeImage(PATH_URL . DIR_UPLOAD_NEWS . $items_2[$i]->image, 135);
                        }
                    } else {
                        $imga = img(PATH_URL . "assets/images/img/no-image.jpg", 135, 79);
                    }
                    $bien1 = $items_2[$i]->slug;
                    $ngay = date("d/m/y", strtotime($items_2[$i]->created));
                    $title = CutText($items_2[$i]->title, 50);
                    $des = CutText($items_2[$i]->description, 100);
                    $html .= '<div class="hot">
				                <div class="img left">
				                    <a href="' . $bien1 . '" target="_blank"><img src="' . $imga . '" alt="" width="135" height="79" class="dblock" /></a>
						                </div>
						                <div class="detail left">
						                    <a href="' . $bien1 . '" target="_blank"><h1>' . $title . '</h1></a>
						                    <span>Được đăng ngày ' . $ngay . '</span>
						                    <div class="clearAll"></div>
						                    <div class="des">' . $des . '
							                    </div>
							
							                </div>
					         		   </div>
		         		   <div class="clearAll"></div>
		         		   <div style="height: 10px;"></div>
		         		   <div style=" border-bottom: 1px dotted #3e3832;"></div>';
                }

            }

            $retval->html = $html;
            echo json_encode($retval);
        } else {
            return $retval;
        }
    }

    /*------------------------------------ End FRONTEND --------------------------------*/
}